// import Toast from 'tdesign-miniprogram/toast/index';
import { post_appointmentInfo } from '../../../services/appointment/index.js';

// import { fetchActivityList } from '../../../services/activity/fetchActivityList';
// import {
//   getGoodsDetailsCommentList,
//   getGoodsDetailsCommentsCount,
// } from '../../../services/good/fetchGoodsDetailsComments';

// import { cdnBase, Base_Api } from '../../../config/index';

// const imgPrefix = `${cdnBase}/`;

// const recLeftImg = `${imgPrefix}common/rec-left.png`;
// const recRightImg = `${imgPrefix}common/rec-right.png`;
// const obj2Params = (obj = {}, encode = false) => {
//   const result = [];
//   Object.keys(obj).forEach((key) =>
//     result.push(`${key}=${encode ? encodeURIComponent(obj[key]) : obj[key]}`),
//   );

//   return result.join('&');
// };


import Message from 'tdesign-miniprogram/message/index';

Page({
  data: {
    resultObj: {
      is_showResult: false,
      title: '预约成功',
      desc: '描述信息',
      theme: 'success'
    },

    goodsId: "",
    calendar_visible: false,
    date_visible: false,
    sel_time: '',
    timeType: 0,
    formData: {
      name: '',
      name_status: 'default',
      tel: '',
      tel_status: 'default',
      address1: '',
      address1_status: 'default',
      address2: '',
      address2_status: 'default',
      time1: '',
      time1_status: 'default',
      time2: '',
      time2_status: 'default',
      time3: '',
      time3_status: 'default',
      num: '',
      num_status: 'default'
    },
    locationData: {}
  },

  builtInSearch({ code, name }) {
    return new Promise((resolve, reject) => {
      wx.getSetting({
        success: (res) => {
          console.log("设置信息： ", res)
          if (res.authSetting[code] === false) {
            wx.showModal({
              title: `获取${name}失败`,
              content: `获取${name}失败，请在【右上角】-小程序【设置】项中，将【${name}】开启。`,
              confirmText: '去设置',
              confirmColor: '#FA550F',
              cancelColor: '取消',
              success(res) {
                if (res.confirm) {
                  wx.openSetting({
                    success(settinRes) {
                      if (settinRes.authSetting[code] === true) {
                        resolve();
                      } else {
                        console.warn('用户未打开权限', name, code);
                        reject();
                      }
                    },
                  });
                } else {
                  reject();
                }
              },
              fail() {
                reject();
              },
            });
          } else {
            resolve();
          }
        },
        fail(err) {
          console.log("设置信息失败。。。", err)
          reject();
        },
      });
    });
  },

  onInputBlur(e) {
    // if (!e.detail.value) {
    //   this.setData({
    //     [`formData.${e.target.dataset.prop}_status`]: 'error'
    //   })

    //   console.log(this.data)
    // }
  },

  routeTodOrder_fn() {
    console.log("跳转到订单信息")
  },

  onInputChange(event) {
    // 更新输入值
    this.setData({
      [`formData.${event.target.dataset.prop}`]: event.detail.value
    });
  },
  timeFocus_fn(cc) {
    this.setData({
      timeType: cc.target.dataset.timetype,
      sel_time: this.data.formData[`time${cc.target.dataset.timetype}`]
    })
    if (cc.target.dataset.timetype == 1) {
      this.setData({
        calendar_visible: true
      })
    } else {
      this.setData({
        date_visible: true
      })
    }

  },

  calendar_confirm(e) {
    const { value } = e.detail;
    const format = (val) => {
      const date = new Date(val);
      return `${date.getFullYear()}-${date.getMonth() + 1}-${date.getDate()}`;
    };
    this.setData({
      'formData.time1': format(value),
    });

  },

  calendar_close() {
    this.setData({
      calendar_visible: false
    })
  },

  date_confirm(e) {


    this.setData({
      [`formData.time${this.data.timeType}`]: e.detail.value,
      date_visible: false
    })


    // this.setData({
    //   [mode]: value,
    //   [`${mode}Text`]: value,
    // });

    // this.hidePicker();
  },


  submit_btn() {


    let str = ''
    if (!this.data.formData.name) {
      str = "请输入用户名"
    } else if (!this.data.formData.tel) {
      str = "请输入联系方式"
    } else if (!this.data.formData.time1) {
      str = "请选择日期"
    } else if (!this.data.formData.time2) {
      str = "请选择开始时间"
    } else if (!this.data.formData.time3) {
      str = "请选择结束时间"
    } else if (!this.data.formData.num) {
      str = "请输入服务数量"
    } else if (!this.data.formData.address1) {
      str = "请选择联系地址"
    } else if (!this.data.formData.address2) {
      str = "请输入楼栋或具体门牌信息"
    }

    if (str) {
      Message.warning({
        context: this,
        offset: [10, 32],
        duration: 2000,
        content: str,
        closeBtn: true
      });
    } else {
      let params = Object.assign(this.data.formData, { goodsId: this.data.goodsId })
      post_appointmentInfo(params).then((res) => {
        if (res.value.code == 200) {
          this.setData({
            'resultObj.is_showResult': true
          })
        }

      }).catch((err) => {

      })

    }
  },

  onLoad(query) {
    const { goodsId } = query;
    this.setData({
      goodsId: goodsId,
    });
    // this.getDetail(spuId);
    // this.getCommentsList(spuId);
    // this.getCommentsStatistics(spuId);
  },

  mapIcon_click(e) {

    this.builtInSearch({ code: 'scope.userLocation', name: '地址位置' }).then(() => {
      wx.chooseLocation({
        success: (res) => {
          if (res.name) {
            console.log("选中地点成功", res)
            this.setData({
              locationData: res,
              'formData.address1': res.address + res.name
            })

            // this.triggerEvent('addressParse', {
            //   address: res.address,
            //   name: res.name,
            //   latitude: res.latitude,
            //   longitude: res.longitude,
            // });
          } else {
            Toast({
              context: this,
              selector: '#t-toast',
              message: '地点为空，请重新选择',
              icon: '',
              duration: 1000,
            });
          }
        },
        fail: function (res) {
          console.warn(`wx.chooseLocation fail: ${JSON.stringify(res)}`);
          if (res.errMsg !== 'chooseLocation:fail cancel') {
            Toast({
              context: this,
              selector: '#t-toast',
              message: '地点错误，请重新选择',
              icon: '',
              duration: 1000,
            });
          }
        },
      });
    }).catch((err) => {
      console.log("444444")
      console.log(err)
    })
  },


});
